package _05多线程实现多人同时上传;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

public class UploadRunnable implements Runnable{

    private Socket socket ;

    public UploadRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        String fileName = "day12\\服务端文件夹\\"+UUID.randomUUID().toString()+".jpg";
        try (
                //创建文件输出流用于下载客户端传入的文件
                FileOutputStream fos =new FileOutputStream(fileName);

                //通过socket对象创建输入流读取客户端文件
                InputStream socketInputStream = socket.getInputStream();
                //通过socket对象创建输出流读取客户端文件
                OutputStream socketOutputStream = socket.getOutputStream()
        ){


            byte[] bytes = new byte[1024];
            int read;
            //读取客户端上传文件
            while ((read=socketInputStream.read(bytes))!=-1){
                fos.write(bytes,0,read);
            }
            System.out.println("服务器端下载完成");

            //回写数据
            socketOutputStream.write("文件已下载".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            File file = new File(fileName);
            final boolean delete = file.delete();
            System.out.println("文件已删除");
        }


    }
}
